package org.skydiveapphd;

import org.skydiveapphd.ui.FragmentHelper;
import org.skydiveapphd.ui.LogEntryListCursorAdapter;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.repository.LogEntryRepository;
import org.skydiveapplibrary.ui.NumberDialog;
import org.skydiveapplibrary.ui.NumberDialog.OnNumberSetListener;

import android.app.ListFragment;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class LogEntryListActivity extends ListFragment
{
	// repository
	private LogEntryRepository repository;
	private Cursor cursor;
	
	// data
	private int requestedRowId;

	// requestFragment Results
	private static final int FRAGMENT_REQUEST_ALLOWED = 10;
	private static final int FRAGMENT_REQUEST_DENIED = 20;
	private static final int FRAGMENT_REQUEST_POSTPONED = 30;
	
	// listeners
	private OnClickListener addListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			FragmentHelper.getInstance();
			int launchResult = FragmentHelper.requestFragment(LogEntryEditActivity.newInstance(new Bundle()), android.R.id.tabhost, 
							Constants.TAG_LOG_ENTRY_EDIT, getFragmentManager());
			if (launchResult == FRAGMENT_REQUEST_DENIED)
				showFailedFragmentLaunchMessage();
		}
	};
	
	private OnClickListener copyListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			Bundle args = new Bundle();
			args.putBoolean(Constants.EXTRA_LOG_ENTRY_COPY, true);
			
			FragmentHelper.getInstance();
			int launchResult = FragmentHelper.requestFragment(LogEntryEditActivity.newInstance(args), android.R.id.tabhost, 
					Constants.TAG_LOG_ENTRY_EDIT, getFragmentManager());
			if (launchResult == FRAGMENT_REQUEST_DENIED)
				showFailedFragmentLaunchMessage();
		}
	};
	
	private OnClickListener signListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			if (!((LogEntryListCursorAdapter) getListAdapter()).multiSelect)
			{
				if (getFragmentManager().getBackStackEntryCount() == 0)
					toggleSignMode();
				else
					showFailedFragmentLaunchMessage();
			}
			else
			{
				// start signature fragment, pass log entry ids				
				Bundle args = new Bundle();
				args.putIntegerArrayList(Constants.EXTRA_SELECTED_LOG_ENTRY_IDS, ((LogEntryListCursorAdapter)getListAdapter()).getSelection());
				FragmentHelper.getInstance().openFragment(SignatureActivity.newInstance(args), R.id.wholePage, 
						Constants.TAG_SIGN_ENTRIES, getFragmentManager());
			}
		}
	};
	
	private OnClickListener goToListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			// init dialog
    		NumberDialog dialog = new NumberDialog(
    				getActivity(),
    				R.string.log_entry_list_goto_title,
    				1,
    				goToSetListener);
    		// show dialog
    		dialog.show();
		}
	};
	
	// goto number listener
	private OnNumberSetListener goToSetListener = new OnNumberSetListener()
	{
		@Override
		public void onNumberSet(NumberDialog dialog, int number)
		{
			int position = 0;
			try
			{
				cursor.moveToFirst();
				while (cursor.moveToNext())
				{
					if (cursor.getInt(1) == number)
					{
						position = cursor.getPosition();
					}
				}
			}
			finally
			{
				
			}
			getListView().setSelection(position);
		}
	}; 
	
	private OnClickListener cancelListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			toggleSignMode();
		}
	};
		
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		repository = new LogEntryRepository(getActivity());
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    		Bundle savedInstanceState)
	{	
		// Inflate the layout for this fragment
	    View view =  inflater.inflate(R.layout.log_entry_list_view, container, false);
	    
	    // set adapter
    	cursor = repository.getLogEntryCursor();
    	getActivity().startManagingCursor(cursor);
		setListAdapter(new LogEntryListCursorAdapter(getActivity(), cursor));
	    
		// init ui
		initializeUI(view);
		
		return view;
	}
    
   
    public void onResume()
    {
    	super.onResume();

    	getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }
	
    @Override
	public void onListItemClick(ListView lv, View view, int position, long id)
    {
    	if (((LogEntryListCursorAdapter) getListAdapter()).multiSelect)
    	{
	       	// update selection
	       	((LogEntryListCursorAdapter)getListAdapter()).toggleSelection((int)id);
    	}
    	else
    	{  		
			Bundle args = new Bundle();
			args.putInt(Constants.EXTRA_LOG_ENTRY_ID, (int)id);
			FragmentHelper.getInstance();
			int launchResult = FragmentHelper.requestFragment(LogEntryEditActivity.newInstance(args), android.R.id.tabhost, 
					Constants.TAG_LOG_ENTRY_EDIT, getFragmentManager());
			
			if (launchResult == FRAGMENT_REQUEST_ALLOWED)
				((LogEntryListCursorAdapter)getListAdapter()).toggleSelection((int)id);
			else if (launchResult == FRAGMENT_REQUEST_DENIED)
				showFailedFragmentLaunchMessage();
			else if (launchResult == FRAGMENT_REQUEST_POSTPONED)
				requestedRowId = (int)id;
    	}
    }
    
	private void initializeUI(View view)
	{
		// set header label
		TextView textView = (TextView) view.findViewById(R.id.LogEntryHeaderTextView);
		textView.setText(R.string.log_book_hd_label);
		
		// add button click listeners
		ImageButton addButton = (ImageButton) view.findViewById(R.id.LogEntryListAddButton);
		addButton.setOnClickListener(addListener);
		
		ImageButton gotoButton = (ImageButton) view.findViewById(R.id.LogEntryListGoToButton);
		gotoButton.setOnClickListener(goToListener);
		
		ImageButton copyButton = (ImageButton) view.findViewById(R.id.LogEntryListCopyButton);
		copyButton.setOnClickListener(copyListener);
		
		ImageButton signButton = (ImageButton) view.findViewById(R.id.LogEntryListSignButton);
		signButton.setOnClickListener(signListener);
		
		ImageButton cancelButton = (ImageButton) view.findViewById(R.id.LogEntryListCancelButton);
		cancelButton.setOnClickListener(cancelListener);
	}
	
	protected void setHeaderText(int id)
    {
		// set header label
		TextView textView = (TextView) getActivity().findViewById(R.id.LogEntryHeaderTextView);
		textView.setText(id);
    }
	
	public void updateListView()
	{
		((LogEntryListCursorAdapter) getListAdapter()).clearSelection();
		cursor.requery();
	}
	
	public void toggleSignMode()
	{
		if (((LogEntryListCursorAdapter) getListAdapter()).multiSelect)
		{
			getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			((LogEntryListCursorAdapter) getListAdapter()).multiSelect = false;
			((LogEntryListCursorAdapter) getListAdapter()).clearSelection();
			updateListView();
			setHeaderText(R.string.log_book_label);
			
			setButtonVisibility(R.id.LogEntryListCancelButton, View.GONE);
			setButtonVisibility(R.id.LogEntryListAddButton, View.VISIBLE);
			setButtonVisibility(R.id.LogEntryListCopyButton, View.VISIBLE);
			setButtonVisibility(R.id.LogEntryListGoToButton, View.VISIBLE);
		}
		else
		{
			getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			((LogEntryListCursorAdapter) getListAdapter()).multiSelect = true;
			updateListView();
			setHeaderText(R.string.log_entry_list_select_label);
			
			setButtonVisibility(R.id.LogEntryListCancelButton, View.VISIBLE);
			setButtonVisibility(R.id.LogEntryListAddButton, View.GONE);
			setButtonVisibility(R.id.LogEntryListCopyButton, View.GONE);
			setButtonVisibility(R.id.LogEntryListGoToButton, View.GONE);
		}
	}
	
	private void setButtonVisibility(int id, int visibility)
	{
		ImageButton imageButton = (ImageButton) getActivity().findViewById(id);
		imageButton.setVisibility(visibility);
	}
	
	private void showFailedFragmentLaunchMessage()
	{
		Toast.makeText(getActivity(), "Please finish other tasks before launching this function", Toast.LENGTH_LONG).show();
	}
	
	public void highlightRequestedRow()
	{
		((LogEntryListCursorAdapter)getListAdapter()).toggleSelection(requestedRowId);
	}
}